package com.ml.carManager.ui.diver;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.amap.api.maps.MapsInitializer;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.hjq.toast.ToastUtils;
import com.ml.carManager.R;
import com.ml.carManager.entity.TabEntity;
import com.ml.carManager.net.NetProxyListener;
import com.ml.carManager.ui.dialog.ChoiceListDialog;
import com.ml.carManager.ui.diver.adapter.OrderAdapter;
import com.ml.carManager.ui.diver.order.OrderDetailActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import custom.base.entity.order.OrderList;
import custom.base.entity.order.OrderPage;
import custom.base.entity.base.BaseResponse;
import custom.base.entity.company.Company;
import custom.base.entity.company.Project;
import custom.base.ui.adapter.BaseRecyclerAdapter;
import custom.base.ui.decoration.DecorationLine;
import custom.base.ui.decoration.DecorationSpaceItem;
import custom.base.ui.fragment.BaseFragment;
import custom.base.utils.TxtUtil;
import custom.base.utils.store.ConstantsPreference;
import custom.base.utils.store.PreferencesManager;
import custom.base.widgets.LoadLayout;
import custom.base.widgets.recyclerview.AutoLoadRecyclerView;
import custom.base.widgets.recyclerview.callback.LoadMoreListener;
import custom.captcha.utils.DisplayUtil;
import retrofit2.Call;

import static custom.base.widgets.LoadLayout.TYPE_SUCCESS_EMPTY;


public class FragmentHome extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, LoadMoreListener {
    @BindView(R.id.fragment_main_diver_home_tab)
    CommonTabLayout tabLayout;
    @BindView(R.id.fragment_main_diver_home_company)
    LinearLayoutCompat llCompany;
    @BindView(R.id.fragment_main_diver_home_project)
    LinearLayoutCompat llProject;
    @BindView(R.id.fragment_main_diver_home_company_text)
    TextView tvCompany;
    @BindView(R.id.fragment_main_diver_home_project_text)
    TextView tvProject;

    @BindView(R.id.fragment_main_diver_home_recyclerview)
    AutoLoadRecyclerView rvList;
    @BindView(R.id.fragment_main_diver_home_refresh)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.loadlayout)
    LoadLayout loadLayout;


    private List<Company> companyList;
    private Company selectCompany = null;

    private List<Project> projectList;
    private Project selectProject = null;

    private ArrayList<CustomTabEntity> tabList = new ArrayList<>();

    private List<OrderList> orderList = new ArrayList<>();
    private OrderAdapter orderAdapter;
    int pageSize = 50;
    int page = 1;
    Integer filterStatus = null;

    /**
     * 碎片界面回复的生命周期
     */
    public void onFragmentResume() {
        super.onFragmentResume();
        onResume();
    }


    @Override
    public void onResume() {
        super.onResume();
        getCompanyList();
        getOrderList();
    }


    @Override
    public int getLayoutID() {
        return R.layout.fragment_main_diver_home;
    }

    @Override
    public void initView(@NonNull View view, @NonNull Bundle savedInstanceState) {
        super.initView(view, savedInstanceState);

        //隐私权限合规校验
        MapsInitializer.updatePrivacyAgree(getActivity(), true);
        MapsInitializer.updatePrivacyShow(getActivity(), true, true);

        refreshLayout.setColorSchemeResources(R.color.app_main_color);

        rvList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.addItemDecoration(new DecorationSpaceItem(DecorationLine.VERTICAL_LIST, DisplayUtil.dip2px(getActivity(), 10f)));

    }

    @Override
    public void initObject(@NonNull Bundle savedInstanceState) {
        super.initObject(savedInstanceState);

        tabList.add(new TabEntity("全部", R.mipmap.ic_launcher, R.mipmap.ic_launcher));
        tabList.add(new TabEntity("未配置", R.mipmap.ic_launcher, R.mipmap.ic_launcher));
        tabList.add(new TabEntity("已配置", R.mipmap.ic_launcher, R.mipmap.ic_launcher));
        tabList.add(new TabEntity("运输中", R.mipmap.ic_launcher, R.mipmap.ic_launcher));
        tabList.add(new TabEntity("警告", R.mipmap.ic_launcher, R.mipmap.ic_launcher));

        selectCompany = (Company) PreferencesManager.getInstance(getActivity()).getObject(ConstantsPreference.LAST_SELECT_COMPANY, Company.class);
        selectProject = (Project) PreferencesManager.getInstance(getActivity()).getObject(ConstantsPreference.LAST_SELECT_PROJECT, Project.class);
    }

    @Override
    public void initData(@NonNull Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        tabLayout.setTabData(tabList);

        orderAdapter = new OrderAdapter(orderList);
        rvList.setAdapter(orderAdapter);
    }


    @Override
    public void initListener() {
        refreshLayout.setOnRefreshListener(this);
        llCompany.setOnClickListener(this);
        llProject.setOnClickListener(this);

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                if (position == 0) {
                    filterStatus = null;
                    getOrderList();
                } else if (position == 1) {
                    filterStatus = 0;
                    getOrderList();
                } else if (position == 2) {
                    filterStatus = 10;
                    getOrderList();
                } else if (position == 3) {
                    filterStatus = 20;
                    getOrderList();
                } else if (position == 4) {
                    filterStatus = 30;
                    getOrderList();
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        orderAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<OrderList>() {
            @Override
            public void onItemClick(View v, int position, OrderList item) {
                Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
                intent.putExtra("orderId", item.getId());
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View v, int clickID) {
        if (llCompany.getId() == clickID) {
            ChoiceListDialog choiceListDialog = new ChoiceListDialog(getActivity());
            List<String> list = new ArrayList<>();
            if (companyList != null)
                for (int i = 0; i < companyList.size(); i++) {
                    list.add(companyList.get(i).getName());
                }
            choiceListDialog.setOnChoiceListItemClickListener(new ChoiceListDialog.OnChoiceListItemClickListener() {
                @Override
                public void onListItemClick(int index) {
                    clickCompany(index);
                }
            });
            choiceListDialog.show(list);
        } else if (llProject.getId() == clickID) {
            if (projectList == null || projectList.size() == 0) {
                ToastUtils.show("未获取到项目");
                return;
            }
            ChoiceListDialog choiceListDialog = new ChoiceListDialog(getActivity());
            List<String> list = new ArrayList<>();
            if (projectList != null)
                for (int i = 0; i < projectList.size(); i++) {
                    list.add(projectList.get(i).getName());
                }
            choiceListDialog.setOnChoiceListItemClickListener(new ChoiceListDialog.OnChoiceListItemClickListener() {
                @Override
                public void onListItemClick(int index) {
                    clickProject(index);
                }
            });
            choiceListDialog.show(list);
        }
    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private void getCompanyList() {
        Call<BaseResponse<List<Company>>> call = appApi.getCompanyList();
        call.enqueue(new NetProxyListener<List<Company>>(getAliveCallback()) {
            @Override
            protected boolean dealNullResponseData() {
                return true;
            }

            @Override
            public void onResponseSuccess(Call call, BaseResponse<List<Company>> response) {
                companyList = response.getData();

                if (companyList == null) {
                    ToastUtils.show("公司加载失败");
                    return;
                }
                if (selectCompany == null) {
                    clickCompany(0);
                } else {
                    for (int i = 0; i < companyList.size(); i++) {
                        if (TxtUtil.equals(companyList.get(i).getId() + "", selectCompany.getId() + "")) {
                            clickCompany(i);
                        }
                    }
                }
            }

            @Override
            public void onResponseError(Call call, Throwable t) {
                super.onResponseError(call, t);
            }

            @Override
            public void onResponseCodeError(Call call, BaseResponse<List<Company>> response) {
                super.onResponseCodeError(call, response);
            }
        });

    }

    private void getCompanyProjectList() {
        if (selectCompany == null) {
            return;
        }
        Call<BaseResponse<List<Project>>> call = appApi.getCompanyProjectList(selectCompany.getId());
        call.enqueue(new NetProxyListener<List<Project>>(getAliveCallback()) {
            @Override
            protected boolean dealNullResponseData() {
                return true;
            }

            @Override
            public void onResponseSuccess(Call call, BaseResponse<List<Project>> response) {
                projectList = response.getData();

                if (projectList == null) {
                    ToastUtils.show("公司加载失败");
                    return;
                }

                if (selectProject == null) {
                    clickProject(0);
                } else {
                    for (int i = 0; i < projectList.size(); i++) {
                        if (projectList.get(i).getId() == selectProject.getId()) {
                            clickProject(i);
                        }
                    }
                }
            }

            @Override
            public void onResponseError(Call call, Throwable t) {
                super.onResponseError(call, t);
            }

            @Override
            public void onResponseCodeError(Call call, BaseResponse<List<Project>> response) {
                super.onResponseCodeError(call, response);
            }
        });

    }

    /**
     * 点击选中公司
     */
    private void clickCompany(int index) {
        if (companyList == null || companyList.size() == 0) {
            return;
        }
        selectCompany = companyList.get(index);

        getCompanyProjectList();
        tvCompany.setText(selectCompany.getName());

        PreferencesManager.getInstance(getActivity()).putObject(ConstantsPreference.LAST_SELECT_COMPANY, selectCompany);
    }

    /**
     * 点击选中项目
     */
    private void clickProject(int index) {
        if (projectList == null || projectList.size() == 0) {
            return;
        }
        selectProject = projectList.get(index);
        tvProject.setText(selectProject.getName());

        PreferencesManager.getInstance(getActivity()).putObject(ConstantsPreference.LAST_SELECT_PROJECT, selectProject);
        getOrderList();
    }

    private void getOrderList() {
        if (selectProject == null) {
            refreshLayout.setRefreshing(false);
            loadLayout.setStatus(TYPE_SUCCESS_EMPTY);
            return;
        }
        refreshLayout.setRefreshing(true);
        Call<BaseResponse<OrderPage>> call = appApi.getOrderList(page, pageSize, selectProject.getId(), filterStatus);
        call.enqueue(new NetProxyListener<OrderPage>(getAliveCallback()) {
            @Override
            protected boolean dealNullResponseData() {
                return true;
            }

            @Override
            protected SwipeRefreshLayout getRefreshLayout() {
                return refreshLayout;
            }

            @Override
            protected LoadLayout getLoadLayout() {
                return loadLayout;
            }

            @Override
            public void onResponseSuccess(Call call, BaseResponse<OrderPage> response) {
                OrderPage orderPage = response.getData();


                List<OrderList> resList = orderPage.getList();

                if (page == 1) {
                    orderList.clear();
                    rvList.loadFinish();
                } else {
                    rvList.loadFinish();
                    if (resList == null || resList.size() < pageSize) {
                        rvList.loadFinish(false);
                    }
                }
                if (resList != null && resList.size() > 0) {
                    orderList.addAll(resList);
                }
                if (orderList.size() == 0)
                    loadLayout.setStatus(TYPE_SUCCESS_EMPTY);
                else
                    loadLayout.setStatus(LoadLayout.TYPE_SUCCESS);
                orderAdapter.notifyDataSetChanged();

            }

            @Override
            public void onResponseError(Call call, Throwable t) {
                super.onResponseError(call, t);
            }

            @Override
            public void onResponseCodeError(Call call, BaseResponse<OrderPage> response) {
                super.onResponseCodeError(call, response);
            }
        });

    }


    @Override
    public void onRefresh() {
        page = 1;
        getOrderList();
    }

    @Override
    public void loadMore() {
        page++;
        getOrderList();
    }
}
